package com.jalarbee.liquid.security;

import com.jalarbee.core.user.business.User;
import com.jalarbee.core.user.dao.exception.NoSuchUserFound;
import com.jalarbee.core.user.service.UserService;
import javax.inject.Inject;
import javax.inject.Named;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

/**
 *
 * @author Abdoulaye <b>Ikhnaton</b> Diallo
 */

@Named("userDetailsService")
public class SecurityUserDetailsService implements UserDetailsService {

    @Inject
    private UserService userService;
    
    private static final Logger LOGGER = LoggerFactory.getLogger(SecurityUserDetailsService.class);

    public UserDetails loadUserByUsername(String string) throws UsernameNotFoundException, DataAccessException {
        User user;
        try {
            user = userService.findUserByName(string);
        } catch (NoSuchUserFound nsuf) {
            LOGGER.warn(nsuf.getMessage(), nsuf);
            throw new UsernameNotFoundException(nsuf.getMessage());
        }
        if (user != null) {
            return new SecurityUserDetails(user.getCredentials().getPassword(), user.getCredentials().getUsername(), user.getRoles(), true, true, true, true);
        }
        return null;
    }
}
